//
//  QrCodeImgUtil.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/2/18.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class QrCodeImgUtil: NSObject {
    
    static let shareInstance:QrCodeImgUtil = {
        return QrCodeImgUtil()
    }()
    
    // 生成二维码
    func generateQRCodeImg(_ qrStr: String, qrImgName: String? = nil) -> UIImage {
        // 生成二维码
        let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
        qrFilter.setDefaults()
        qrFilter.setValue(qrStr.data(using: String.Encoding.utf8), forKey: "inputMessage")
        let ciImage = qrFilter.outputImage
        // 缩放处理
        let transform = CGAffineTransform(scaleX: 10, y: 10)
        let transformImage = ciImage?.transformed(by: transform)
        // 颜色滤镜
        let colorFilter = CIFilter(name: "CIFalseColor")!
        colorFilter.setDefaults()
        colorFilter.setValue(transformImage, forKey: "inputImage")
        // 前景色
        colorFilter.setValue(CIColor(color: UIColor.black), forKey: "inputColor0")
        // 背景色
        colorFilter.setValue(CIColor(color: UIColor.white), forKey: "inputColor1")
        
        let outputImage = colorFilter.outputImage
        var scanImg = UIImage.init(ciImage: outputImage!)
        if qrImgName != nil {
            scanImg = insertAvatarImage(qrimage: UIImage.init(ciImage: outputImage!), image: UIImage(named: qrImgName!)!)
        }
        return scanImg
    }
    
    private func insertAvatarImage(qrimage: UIImage, image: UIImage) -> UIImage {
        // 开启上下文
        UIGraphicsBeginImageContext(qrimage.size)
        let rect = CGRect(origin: CGPoint.zero, size: qrimage.size)
        qrimage.draw(in: rect)
        // 位置
        let w = rect.width * 0.2
        let x = (rect.width - w) * 0.5
        let y = (rect.height - w) * 0.5
        image.draw(in: CGRect(x: x, y: y, width: w, height: w))
        // 画圈
        let radius = w * 0.5
        let center = CGPoint(x: x + radius, y: y + radius)
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: false)
        path.lineWidth = 10
        UIColor.white.setStroke()
        path.stroke()
        // 获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭渲染
        UIGraphicsEndImageContext()
        return image!
    }
}
